package com.smart.util;

import java.util.Date;

import com.smart.constants.SmartConstants;
import com.smart.model.AccessToken;

import net.sf.json.JSONObject;


public class AccessTokenManager {
  private static AccessToken accessToken;
  private static long getTime;
  public static boolean isExpired()
  {
	  Date d=new Date();
	  //计算当前到现在经过了多少秒
	  long interval=(d.getTime()-getTime)/1000;
	  if(interval>accessToken.getExpires_in()-3) //之所以减去3秒，是考虑程序等会执行时AccessToken可能会过期
             return true;
	  else return false;
  }
  public static AccessToken getAccessToken()
  {
	  System.out.println("开始获取token");
	  if(accessToken==null||isExpired())
	  {
		  //如果AccessToken为空，则必须先初始化AccessToken
		  if(accessToken==null)   accessToken=new AccessToken();
		  String url=SmartConstants.ACCESS_TOKEN_URL.replace("APPID",SmartConstants.APPID).replace("APPSECRET",SmartConstants.APPSECRET);
		  JSONObject jsonObject=WeixinUtil.doGetStr(url);
		  if(jsonObject!=null)
		  {
			  System.out.println("获取accessToken成功");
			  System.out.println(jsonObject);
			  accessToken.setToken(jsonObject.getString("access_token"));
			  accessToken.setExpires_in(jsonObject.getInt("expires_in"));
			  getTime=new Date().getTime();
		  }
		  else
		  {
			  System.out.println("获取accessToken失败");
		  }
	  }
	  return accessToken;
  }
}
